package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.beans.TableProcess;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.*;
import java.util.*;

/**
 * @author Felix
 * @date 2023/7/29
 * 维度数据的过滤处理
 */
public class TableProcessFunction extends BroadcastProcessFunction<JSONObject, TableProcess, JSONObject> {

    private Map<String,TableProcess> configMap = new HashMap<>();

    private MapStateDescriptor<String, TableProcess> mapStateDescriptor;

    public TableProcessFunction(MapStateDescriptor<String, TableProcess> mapStateDescriptor) {
        this.mapStateDescriptor = mapStateDescriptor;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        //提前将配置表中的配置信息预加载到程序中configMap
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //建立连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/gmall0222_config?user=root&password=123456&useUnicode=true&characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");
        //获取数据库操作对象
        String sql = "select * from gmall0222_config.table_process_dim ";
        PreparedStatement ps = conn.prepareStatement(sql);
        //执行SQL语句
        ResultSet rs = ps.executeQuery();
        //处理结果集
        ResultSetMetaData metaData = rs.getMetaData();
        while (rs.next()){
            //定义一个json对象接收一行查询结果
            JSONObject jsonObj = new JSONObject();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object columnValue = rs.getObject(i);
                jsonObj.put(columnName,columnValue);
            }
            //将jsonObj转换为TableProcess实体类对象
            TableProcess tableProcess = JSON.toJavaObject(jsonObj, TableProcess.class);
            //将当前这条配置信息放到configMap集合中
            configMap.put(tableProcess.getSourceTable(),tableProcess);
        }
        //释放资源
        rs.close();
        ps.close();
        conn.close();
    }

    //处理主流业务数据
    //根据表名到广播状态中寻找对应的配置信息
    @Override
    public void processElement(JSONObject jsonObj, ReadOnlyContext ctx, Collector<JSONObject> out) throws Exception {
        // System.out.println(jsonObj);
        //获取处理的业务数据库表表名
        String table = jsonObj.getString("table");
        //获取广播状态
        ReadOnlyBroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //根据表名到广播状态中获取对应的配置信息
        TableProcess tableProcess = null;

        //判断配置信息是否存在
        if((tableProcess = broadcastState.get(table))!=null
            ||(tableProcess = configMap.get(table))!=null){
            //如果配置信息不为空  说明当前处理的这条业务数据是维度数据  传递到下游
            //只需要传递data内容
            JSONObject dataJsonObj = jsonObj.getJSONObject("data");

            //过滤掉不需要传递的属性
            String sinkColumns = tableProcess.getSinkColumns();
            filterColumn(dataJsonObj,sinkColumns);

            //在向下游传递数据前  补充操作类型
            String type = jsonObj.getString("type");
            dataJsonObj.put("type",type);

            //在向下游传递数据前  补充配置信息
            dataJsonObj.put("table_process",tableProcess);

            out.collect(dataJsonObj);
        }

    }

    //过滤掉不需要传递的属性
    //dataJsonObj:{"tm_name":"苹果111","create_time":"2021-12-14 00:00:00","logo_url":"/static/default.jpg2323","id":2}
    //sinkColumns: id,tm_name
    private void filterColumn(JSONObject dataJsonObj, String sinkColumns) {
        //获取保留的字段
        String[] columnArr = sinkColumns.split(",");
        List<String> columnList = Arrays.asList(columnArr);
        //获取json中的每一个键值对
        Set<Map.Entry<String, Object>> entrySet = dataJsonObj.entrySet();
        entrySet.removeIf(entry->!columnList.contains(entry.getKey()));
    }

    //处理广播流配置数据
    //将读取到的配置信息放到广播状态中或者从广播状态中删除配置信息
    @Override
    public void processBroadcastElement(TableProcess tableProcess, Context ctx, Collector<JSONObject> out) throws Exception {
        //获取对配置表进行的操作的类型
        String op = tableProcess.getOp();
        //获取广播状态
        BroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //获取配置表中配置的维度表表名   作为广播状态中的key
        String sourceTable = tableProcess.getSourceTable();
        if("d".equals(op)){
            //对配置表做了删除操作    将广播状态中对应的配置信息删除掉
            broadcastState.remove(sourceTable);
            configMap.remove(sourceTable);
        }else{
            //对配置表做了删除外的其它操作    将对应配置信息放到或者更新到广播状态中
            broadcastState.put(sourceTable,tableProcess);
            configMap.put(sourceTable,tableProcess);
        }
    }
}
